package com.stock_t.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stock_t.entity.StockPendingBuyPool;
import com.stock_t.entity.StockPool;
import com.stock_t.entity.StockTrading;
import com.stock_t.page.TableDataInfo;
import com.stock_t.service.StockPendingBuyPoolService;
import com.stock_t.service.StockPoolService;
import com.stock_t.service.StockTTransactionService;
import com.stock_t.service.StockTradingService;
import com.stock_t.utils.MapUtils;
import com.stock_t.utils.PageUtils;
import com.stock_t.utils.QueryWrapperUtils;
import com.stock_t.utils.EastMoneyFundFlowUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 股票交易控制器
 */
@Slf4j
@RestController
@RequestMapping("/stock/trading")
public class StockTradingController {

    // 额外的补录数据
    public static Map<String, BigDecimal> extraInfo = new HashMap<String, BigDecimal>();
    static{
//        //医疗ETF
//        extraInfo.put("512170", new BigDecimal("23.96"));
//        //酒ETF
//        extraInfo.put("512690", new BigDecimal("7.98"));
        // 军工ETF
//        extraInfo.put("512660", new BigDecimal("-798.18"));
        // 医疗创新
//        extraInfo.put("516820", new BigDecimal("-20.02"));
        // 新能源E
//        extraInfo.put("516090", new BigDecimal("55.98"));
        // 创业版成长ET
//        extraInfo.put("159967", new BigDecimal("147.96"));
    }


    @Autowired
    private StockTradingService stockTradingService;

    @Autowired
    private StockPoolService stockPoolService;

    @Autowired
    private StockPendingBuyPoolService stockPendingBuyPoolService;

    @Autowired
    private StockTTransactionService stockTTransactionService;

    /**
     * 获取股票交易列表
     */
    @PostMapping("/list")
    public Map<String, Object> list(@RequestBody StockTrading stockTrading) {
        QueryWrapper<StockTrading> queryWrapper = new QueryWrapper<>(stockTrading);
        List<StockTrading> list = stockTradingService.list(queryWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", list);
        result.put("msg", "success");
        return result;
    }

    /**
     * 分页查询股票交易
     */
    @PostMapping("/page")
    public TableDataInfo page(@RequestBody StockTrading stockTrading) {
        // 使用PageUtils开启分页
        Page<StockTrading> page = PageUtils.startPage();
        log.info("分页查询股票交易，查询条件：{}", stockTrading);
        // 构建查询条件
        QueryWrapper<StockTrading> queryWrapper = QueryWrapperUtils.createQueryWrapper(stockTrading);
        stockTradingService.page(page, queryWrapper);

        return PageUtils.getDataTable(page);
    }

    /**
     * 根据ID获取股票交易
     */
    @GetMapping("/{id}")
    public Map<String, Object> getById(@PathVariable("id") Long id) {
        StockTrading stockTrading = stockTradingService.getById(id);

        Map<String, Object> result = new HashMap<>();
        if (stockTrading != null) {
            result.put("code", 200);
            result.put("data", stockTrading);
            result.put("msg", "success");
        } else {
            result.put("code", 404);
            result.put("msg", "股票交易不存在");
        }

        return result;
    }

    /**
     * 保存股票交易（新增或更新）
     */
    @PostMapping("/save")
    public Map<String, Object> save(@RequestBody StockTrading stockTrading) {
        log.info("接收到的StockTrading对象: {}", JSONObject.toJSONString(stockTrading));
        log.info("tProfit字段值: {}", stockTrading.getTprofit());

        boolean success = stockTradingService.saveOrUpdateWithCheck(stockTrading);

        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("msg", "保存成功");
        } else {
            result.put("code", 500);
            result.put("msg", "保存失败");
        }

        return result;
    }

    /**
     * 更新股票交易
     */
    @PutMapping("/update")
    public Map<String, Object> update(@RequestBody StockTrading stockTrading) {
        // 确保记录存在
        StockTrading existStockTrading = stockTradingService.getById(stockTrading.getId());

        Map<String, Object> result = new HashMap<>();
        if (existStockTrading == null) {
            result.put("code", 404);
            result.put("msg", "股票交易不存在");
            return result;
        }

        boolean success = stockTradingService.updateById(stockTrading);

        if (success) {
            result.put("code", 200);
            result.put("msg", "更新成功");
        } else {
            result.put("code", 500);
            result.put("msg", "更新失败");
        }

        return result;
    }

    /**
     * 删除股票交易
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable("id") Long id) {
        // 确保记录存在
        StockTrading existStockTrading = stockTradingService.getById(id);

        Map<String, Object> result = new HashMap<>();
        if (existStockTrading == null) {
            result.put("code", 404);
            result.put("msg", "股票交易不存在");
            return result;
        }

        boolean success = stockTradingService.removeById(id);

        if (success) {
            result.put("code", 200);
            result.put("msg", "删除成功");
        } else {
            result.put("code", 500);
            result.put("msg", "删除失败");
        }

        return result;
    }

    /**
     * 批量删除股票交易
     */
    @DeleteMapping("/batch")
    public Map<String, Object> batchDelete(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 400);
            result.put("msg", "请选择要删除的记录");
            return result;
        }

        boolean success = stockTradingService.removeByIds(ids);

        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("msg", "批量删除成功");
        } else {
            result.put("code", 500);
            result.put("msg", "批量删除失败");
        }

        return result;
    }

    /**
     * 同步指定日期和股票的做T收益
     */
    @PostMapping("/sync-t-profit")
    public Map<String, Object> syncTProfit(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();

        try {
            String tradeDateStr = (String) params.get("tradeDate");
            String stockCode = (String) params.get("stockCode");

            if (tradeDateStr == null || stockCode == null) {
                result.put("code", 400);
                result.put("msg", "交易日期和股票编码不能为空");
                return result;
            }

            // 转换日期格式
            Date tradeDate = new SimpleDateFormat("yyyy-MM-dd").parse(tradeDateStr);

            boolean success = stockTradingService.syncTProfit(tradeDate, stockCode);

            if (success) {
                result.put("code", 200);
                result.put("msg", "同步做T收益成功");
            } else {
                result.put("code", 500);
                result.put("msg", "同步做T收益失败");
            }
        } catch (Exception e) {
            log.error("同步做T收益接口异常", e);
            result.put("code", 500);
            result.put("msg", "同步做T收益异常：" + e.getMessage());
        }

        return result;
    }

    /**
     * 同步指定日期所有股票的做T收益
     */
    @PostMapping("/sync-all-t-profit")
    public Map<String, Object> syncAllTProfitByDate(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();

        try {
            String tradeDateStr = (String) params.get("tradeDate");

            if (tradeDateStr == null) {
                result.put("code", 400);
                result.put("msg", "交易日期不能为空");
                return result;
            }

            // 转换日期格式
            Date tradeDate = new SimpleDateFormat("yyyy-MM-dd").parse(tradeDateStr);

            int successCount = stockTradingService.syncAllTProfitByDate(tradeDate);

            result.put("code", 200);
            result.put("msg", String.format("成功同步 %d 只股票的做T收益", successCount));
            result.put("data", successCount);
        } catch (Exception e) {
            log.error("批量同步做T收益接口异常", e);
            result.put("code", 500);
            result.put("msg", "批量同步做T收益异常：" + e.getMessage());
        }

        return result;
    }

    /**
     * 获取预定义的股票列表（股票编号和名称）
     */
    @GetMapping("/stocks")
    public Map<String, Object> getStockList() {
        List<Map<String, String>> stockList = new ArrayList<>();
        // 创建预定义的股票列表（手动配置）用于调整顺序
        addStock(stockList, "512170", "医疗ETF");
        List<Map<String, String>> stockDatabase = stockTradingService.getStockList();
        // 使用addStock方法添加股票
        for (Map<String, String> stringStringMap : stockDatabase) {
            addStock(stockList, stringStringMap.get("stockCode"), stringStringMap.get("stockName"));
        }

        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", stockList);
        result.put("msg", "success");

        return result;
    }

    /**
     * 获取当前存在的股票（股票池中股数大于待买入池中股数的股票）
     */
    @GetMapping("/current-stocks")
    public Map<String, Object> getCurrentStocks() {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 获取所有股票池中的股票
            List<StockPool> stockPoolList = stockPoolService.list();
            log.info("股票池中共有 {} 只股票", stockPoolList.size());

            // 2. 获取所有待买入池中的股票
            List<StockPendingBuyPool> pendingBuyList = stockPendingBuyPoolService.list();
            log.info("待买入池中共有 {} 只股票", pendingBuyList.size());

            // 3. 按股票编码统计股票池中的总股数
            Map<String, Integer> stockPoolShares = new HashMap<>();
            Map<String, String> stockNames = new HashMap<>();

            for (StockPool stock : stockPoolList) {
                String stockCode = stock.getStockCode();
                Integer shares = stock.getBuyShares();

                stockPoolShares.put(stockCode,
                        stockPoolShares.getOrDefault(stockCode, 0) + shares);
                stockNames.put(stockCode, stock.getStockName());
            }

            // 4. 按股票编码统计待买入池中的总股数
            Map<String, Integer> pendingBuyShares = new HashMap<>();

            for (StockPendingBuyPool stock : pendingBuyList) {
                String stockCode = stock.getStockCode();
                Integer shares = stock.getBuyShares();

                pendingBuyShares.put(stockCode,
                        pendingBuyShares.getOrDefault(stockCode, 0) + shares);
            }

            // 5. 计算当前存在的股票（股票池股数 - 待买入池股数 > 0）
            List<Map<String, Object>> currentStocks = new ArrayList<>();

            for (Map.Entry<String, Integer> entry : stockPoolShares.entrySet()) {
                String stockCode = entry.getKey();
                Integer poolShares = entry.getValue();
                Integer pendingShares = pendingBuyShares.getOrDefault(stockCode, 0);

                // 计算剩余股数
                Integer remainingShares = poolShares - pendingShares;

                log.info("股票 {} - 股票池股数: {}, 待买入池股数: {}, 剩余股数: {}",
                        stockCode, poolShares, pendingShares, remainingShares);

                // 剩余股数大于0的就是当前存在的股票
                if (remainingShares > 0) {
                    Map<String, Object> stockInfo = new HashMap<>();
                    stockInfo.put("stockCode", stockCode);
                    stockInfo.put("stockName", stockNames.get(stockCode));
                    stockInfo.put("poolShares", poolShares);
                    stockInfo.put("pendingShares", pendingShares);
                    stockInfo.put("remainingShares", remainingShares);

                    currentStocks.add(stockInfo);
                }
            }

            log.info("当前存在的股票共 {} 只", currentStocks.size());

            // 6. 遍历这些股票（这里可以根据需要添加具体的遍历逻辑）
            for (Map<String, Object> stock : currentStocks) {
                String stockCode = (String) stock.get("stockCode");
                String stockName = (String) stock.get("stockName");
                Integer remainingShares = (Integer) stock.get("remainingShares");

                log.info("遍历股票: {} - {}, 剩余股数: {}", stockCode, stockName, remainingShares);
                // TODO: 在这里添加对每只股票的具体处理逻辑
            }

            result.put("code", 200);
            result.put("data", currentStocks);
            result.put("msg", "获取当前存在的股票成功");

        } catch (Exception e) {
            log.error("获取当前存在的股票异常", e);
            result.put("code", 500);
            result.put("msg", "获取当前存在的股票异常：" + e.getMessage());
        }

        return result;
    }

    // 添加一个API用于同步股票状态 处理单只股票 传入股票编码

    /**
     * 同步单只股票状态（根据股票编码查询最新信息并检查今天的数据）
     */
    @PostMapping("/sync-stock-status")
    public Map<String, Object> syncStockStatus(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();

        try {
            String stockCode = (String) params.get("stockCode");

            if (stockCode == null || stockCode.trim().isEmpty()) {
                result.put("code", 400);
                result.put("msg", "股票编码不能为空");
                return result;
            }

            log.info("开始同步股票 {} 的状态", stockCode);

            // 1. 根据股票编码查询最新的股票信息
            StockTrading latestStockInfo = getLatestStockInfo(stockCode);

            if (latestStockInfo == null) {
                result.put("code", 404);
                result.put("msg", "未找到股票 " + stockCode + " 的历史数据");
                return result;
            }

            log.info("查询到股票 {} 的最新信息: {}", stockCode, latestStockInfo.getTradeDate());

            Date today = new Date();

            // 3. 如果今天的数据不存在，则基于最新数据生成今天的数据
            log.info("股票 {} 的今日数据不存在，开始生成", stockCode);

            StockTrading todayStockTrading = createTodayStockTrading(latestStockInfo);
            boolean saveSuccess = stockTradingService.saveOrUpdateWithCheck(todayStockTrading);

            if (saveSuccess) {
                log.info("成功生成股票 {} 的今日数据", stockCode);
                result.put("code", 200);
                result.put("msg", "成功生成股票 " + stockCode + " 的今日数据");
                result.put("data", MapUtils.of(
                        "stockCode", stockCode,
                        "action", "created_today",
                        "message", "已生成今日数据",
                        "tradeDate", new SimpleDateFormat("yyyy-MM-dd").format(today),
                        "basedOnDate", new SimpleDateFormat("yyyy-MM-dd").format(latestStockInfo.getTradeDate())
                ));
            } else {
                log.error("生成股票 {} 的今日数据失败", stockCode);
                result.put("code", 500);
                result.put("msg", "生成股票 " + stockCode + " 的今日数据失败");
            }

        } catch (Exception e) {
            log.error("同步股票状态异常", e);
            result.put("code", 500);
            result.put("msg", "同步股票状态异常：" + e.getMessage());
        }

        return result;
    }

    /**
     * 根据股票编码查询最新的股票信息
     *
     * @param stockCode 股票编码
     * @return 最新的股票交易信息
     */
    private StockTrading getLatestStockInfo(String stockCode) {
        try {
//            extraInfo.put("516820", new BigDecimal("-20.02"));
            // 查询指定股票的最新一条记录（按交易日期降序）
            QueryWrapper<StockTrading> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("stock_code", stockCode)
                    .orderByDesc("trade_date")
                    .last("LIMIT 1");
            StockTrading stockTrading = stockTradingService.getOne(queryWrapper);
//            if(extraInfo.containsKey(stockCode)) {
//                stockTrading.setProfitLoss(stockTrading.getProfitLoss().add(extraInfo.get(stockCode)));
//            }
            return stockTrading;
        } catch (Exception e) {
            log.error("查询股票 {} 最新信息失败", stockCode, e);
            return null;
        }
    }

    /**
     * 基于最新数据创建今天的股票交易数据
     *
     * @param oldStockInfo 最新的股票信息
     * @return 今天的股票交易数据
     */
    private StockTrading createTodayStockTrading(StockTrading oldStockInfo) {
        StockTrading todayTrading = new StockTrading();

        // 复制基本信息
        todayTrading.setStockCode(oldStockInfo.getStockCode());
        todayTrading.setStockName(oldStockInfo.getStockName());
        // 在股票池中获取总的股票数
        StockPool stockPool = new StockPool();
        stockPool.setStockCode(oldStockInfo.getStockCode());
        QueryWrapper<StockPool> queryWrapper = new QueryWrapper<>(stockPool);
        StockPendingBuyPool stockPendingBuyPool = new StockPendingBuyPool();
        stockPendingBuyPool.setStockCode(oldStockInfo.getStockCode());
        QueryWrapper<StockPendingBuyPool> queryWrapper1 = new QueryWrapper<>(stockPendingBuyPool);
        List<StockPool> poolList = stockPoolService.list(queryWrapper);
        List<StockPendingBuyPool> buyPoolList = stockPendingBuyPoolService.list(queryWrapper1);
        BigDecimal totalShares = BigDecimal.ZERO;
        for (StockPool pool : poolList) {
            totalShares = totalShares.add(new BigDecimal(pool.getBuyShares()));
        }
        for (StockPendingBuyPool pendingBuyPool : buyPoolList) {
            totalShares = totalShares.subtract(new BigDecimal(pendingBuyPool.getBuyShares()));
        }
        todayTrading.setTotalShares(totalShares);

        // 设置今天的日期（获取当天最开始的时间 00:00:00）
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date today = calendar.getTime();
        
        todayTrading.setTradeDate(today);
        
        // 计算今天是星期几
        SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE", java.util.Locale.CHINESE);
        todayTrading.setTradeDay(dayFormat.format(today));

        // 获取实时股票价格
        BigDecimal realTimePrice = getRealTimePrice(oldStockInfo.getStockCode());
        
        // 如果获取实时价格成功，使用实时价格；否则使用昨天的价格
        if (realTimePrice != null && realTimePrice.compareTo(BigDecimal.ZERO) > 0) {
            todayTrading.setCurrentPrice(realTimePrice);
            log.info("股票 {} 使用实时价格: {}", oldStockInfo.getStockCode(), realTimePrice);
        } else {
            todayTrading.setCurrentPrice(oldStockInfo.getCurrentPrice());
            log.warn("股票 {} 无法获取实时价格，使用昨天价格: {}", 
                    oldStockInfo.getStockCode(), oldStockInfo.getCurrentPrice());
        }

        // 重新计算市值
        todayTrading.setMarketValue(todayTrading.getTotalShares().multiply(todayTrading.getCurrentPrice()));

        // 动态获取当日做T收益
        BigDecimal todayTProfit = getTodayTProfit(oldStockInfo.getStockCode(), today);
        todayTrading.setTprofit(todayTProfit);

        // 重新计算盈利 - 基于您提供的思路实现
        BigDecimal yesterdayProfitLoss = oldStockInfo.getProfitLoss() != null ? oldStockInfo.getProfitLoss() : BigDecimal.ZERO;
        BigDecimal priceDifference = todayTrading.getCurrentPrice().subtract(oldStockInfo.getCurrentPrice());
        
        // 根据股票数量变化情况计算盈亏
        BigDecimal totalProfitLoss;
        BigDecimal priceChangeProfit = BigDecimal.ZERO;
        // 计算股票数量变化
        BigDecimal sharesChange = todayTrading.getTotalShares().subtract(oldStockInfo.getTotalShares());
        
        if (sharesChange.compareTo(BigDecimal.ZERO) == 0) {
            // 股票数量没有变化
            // (今日股价 - 昨日股价) × 今日股票数量 + 昨日盈亏 + 做T收益
            priceChangeProfit = priceDifference.multiply(todayTrading.getTotalShares());
            totalProfitLoss = priceChangeProfit.add(yesterdayProfitLoss).add(todayTProfit);
            
            log.info("股票数量未变 - 价格变化收益: {}", priceChangeProfit);
            
        } else if (sharesChange.compareTo(BigDecimal.ZERO) > 0) {
            // 股票数量增加了（买入）
            // (今日股价 - 昨日股价) × 昨天股票数量 + (今日股价 - 买入股价) × (今日股票数量 - 昨天股票数量) + 昨日盈亏 + 做T收益

            
            // 从poolList中过滤出今天买入的股票
            List<StockPool> todayBuyList = poolList.stream()
                .filter(pool -> pool.getBuyDate() != null && isSameDay(pool.getBuyDate(), today))
                .collect(Collectors.toList());
                
            log.info("股票 {} 今日买入记录: 总池子数量={}, 今日买入数量={}", 
                    oldStockInfo.getStockCode(), poolList.size(), todayBuyList.size());
            
            // 原有持仓的价格变化收益
            BigDecimal originalProfit = priceDifference.multiply(oldStockInfo.getTotalShares());
            
            // 计算新增持仓的总成本和总收益
            BigDecimal totalNewCost = BigDecimal.ZERO;
            BigDecimal totalNewShares = BigDecimal.ZERO;
            
            for (StockPool buy : todayBuyList) {
                BigDecimal buyShares = new BigDecimal(buy.getBuyShares());
                BigDecimal buyPrice = buy.getBuyPrice();
                if (buyPrice != null) {
                    totalNewCost = totalNewCost.add((realTimePrice.subtract(buy.getBuyPrice())).multiply(buyShares)).subtract(BigDecimal.ONE).subtract(BigDecimal.ONE);
                    totalNewShares = totalNewShares.add(buyShares);
                }
            }
            
            // 验证新增股数是否匹配
            if (totalNewShares.compareTo(sharesChange) != 0) {
                log.warn("股票 {} 新增股数不匹配：计算值={}, 实际值={}", 
                        oldStockInfo.getStockCode(), sharesChange, totalNewShares);
            }
            
            // 新增持仓的收益（基于实际买入成本）
//            BigDecimal newMarketValue = todayTrading.getCurrentPrice().multiply(sharesChange);
//            BigDecimal newProfit = newMarketValue.subtract(totalNewCost);
            
            totalProfitLoss = originalProfit.add(totalNewCost).add(yesterdayProfitLoss).add(todayTProfit);
            
            log.info("股票数量增加 - 原持仓收益: {}, 新增持仓收益: {}, 新增股数: {}, 总成本: {}", 
                    originalProfit, totalNewCost, sharesChange, totalNewCost);
            
        } else {
            // 股票数量减少了（卖出）
            // (今日股价 - 昨日股价) × 今日股票数量 + 昨日盈亏 + 做T收益
            priceChangeProfit = priceDifference.multiply(todayTrading.getTotalShares());
            totalProfitLoss = priceChangeProfit.add(yesterdayProfitLoss).add(todayTProfit);
            
            log.info("股票数量减少 - 剩余持仓收益: {}", priceChangeProfit);
        }
        
        todayTrading.setProfitLoss(totalProfitLoss);
        
        // 重新计算保本价格：根据新的盈亏、当前股价和股票数量计算出保本价格
        // 保本价格 = (市值 - 盈亏) / 股票数量
        BigDecimal newBreakEvenPrice = todayTrading.getMarketValue().subtract(totalProfitLoss)
                .divide(todayTrading.getTotalShares(), 5, BigDecimal.ROUND_HALF_UP);
        todayTrading.setBreakEvenPrice(newBreakEvenPrice);
        
        log.info("盈亏计算详情 - 股票: {}, 昨日股价: {}, 今日股价: {}, 价格变化: {}, 股票数量: {}, 价格变动收益: {}, 昨日盈亏: {}, 做T收益: {}, 总盈亏: {}",
                oldStockInfo.getStockCode(),
                oldStockInfo.getCurrentPrice(),
                todayTrading.getCurrentPrice(),
                priceDifference,
                todayTrading.getTotalShares(),
                priceChangeProfit,
                yesterdayProfitLoss,
                todayTProfit,
                totalProfitLoss);
        
        log.info("保本价计算详情 - 股票: {}, 市值: {}, 盈亏: {}, 股票数量: {}, 新保本价: {}, 原保本价: {}",
                oldStockInfo.getStockCode(),
                todayTrading.getMarketValue(),
                totalProfitLoss,
                todayTrading.getTotalShares(),
                newBreakEvenPrice,
                oldStockInfo.getBreakEvenPrice());

        // 设置创建时间
        todayTrading.setCreatedTime(today);
        todayTrading.setUpdatedTime(today);

        log.info("创建今日股票数据: 股票={}, 日期={}, 股数={}, 当前价={}, 保本价={}, 市值={}, 盈亏={}, 做T收益={}",
                todayTrading.getStockCode(),
                new SimpleDateFormat("yyyy-MM-dd").format(todayTrading.getTradeDate()),
                todayTrading.getTotalShares(),
                todayTrading.getCurrentPrice(),
                todayTrading.getBreakEvenPrice(),
                todayTrading.getMarketValue(),
                todayTrading.getProfitLoss(),
                todayTrading.getTprofit());

        return todayTrading;
    }
    
    /**
     * 判断两个日期是否为同一天
     * @param date1 第一个日期
     * @param date2 第二个日期
     * @return 是否为同一天
     */
    private boolean isSameDay(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        
        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
               cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) &&
               cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取股票实时价格
     * @param stockCode 股票编码
     * @return 实时价格，如果获取失败返回 null
     */
    private BigDecimal getRealTimePrice(String stockCode) {
        try {
            log.info("获取股票 {} 的实时价格", stockCode);
            
            // 使用 EastMoneyFundFlowUtil 获取实时数据
            Map<String, Object> realTimeData = EastMoneyFundFlowUtil.fetchZhengDiefu(stockCode);
            
            if (realTimeData != null && realTimeData.containsKey("收盘价")) {
                Object priceObj = realTimeData.get("收盘价");
                if (priceObj instanceof java.math.BigDecimal) {
                    java.math.BigDecimal price = (java.math.BigDecimal) priceObj;
                    log.info("成功获取股票 {} 实时价格: {}", stockCode, price);
                    return price;
                }
            }
            
            log.warn("股票 {} 的实时数据中未找到有效价格", stockCode);
            return null;
            
        } catch (Exception e) {
            log.error("获取股票 {} 实时价格失败", stockCode, e);
            return null;
        }
    }
      
    /**
     * 获取指定股票当日的做T收益
     * @param stockCode 股票编码
     * @param tradeDate 交易日期
     * @return 当日做T收益，如果获取失败则返回0
     */
    private BigDecimal getTodayTProfit(String stockCode, Date tradeDate) {
        try {
            log.info("获取股票 {} 在 {} 的做T收益", stockCode, new SimpleDateFormat("yyyy-MM-dd").format(tradeDate));

            // 使用 StockTTransactionService 获取当日做T收益
            BigDecimal tProfit = stockTTransactionService.getTotalTProfitByDateAndStock(tradeDate, stockCode);
            
            if (tProfit != null) {
                log.info("成功获取股票 {} 当日做T收益: {}", stockCode, tProfit);
                return tProfit;
            } else {
                log.info("股票 {} 当日暂无做T收益数据，设置为0", stockCode);
                return BigDecimal.ZERO;
            }
            
        } catch (Exception e) {
            log.error("获取股票 {} 当日做T收益失败", stockCode, e);
            return BigDecimal.ZERO;
        }
    }


    /**
     * 添加股票到列表的辅助方法
     *
     * @param stockList 股票列表
     * @param stockCode 股票编码
     * @param stockName 股票名称
     */
    private void addStock(List<Map<String, String>> stockList, String stockCode, String stockName) {
        // 检查是否已存在相同股票编码
        boolean exists = stockList.stream()
                .anyMatch(stock -> stockCode.equals(stock.get("stockCode")));

        // 如果不存在，则添加
        if (!exists) {
            Map<String, String> stock = new HashMap<>();
            stock.put("stockCode", stockCode);
            stock.put("stockName", stockName);
            stockList.add(stock);
        }
    }
}